package com.bitin.module.misc.service;

import com.alibaba.fastjson.JSON;
import com.bitin.common.util.OkHttpClientUtil;
import com.bitin.module.misc.domain.entity.Info;
import com.bitin.module.misc.domain.entity.Level;
import com.bitin.module.misc.domain.entity.Region;
import com.bitin.module.misc.domain.entity.District;
import com.bitin.module.misc.domain.repository.RegionRepository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class RegionServiceImpl implements RegionService {
    private final RegionRepository regionRepository;

    public RegionServiceImpl(RegionRepository regionRepository) {
        this.regionRepository = regionRepository;
    }

    @Override
    @Transactional
    public List<Region> copy(String keywords, String subdistrict, String extensions){
        Info info = findInfo(keywords, subdistrict, extensions);
        return this.regionRepository.saveAll(info.getDistricts().stream().map(District::toRegion).collect(Collectors.toList()));
    }

    @Override
    @Transactional
    public void syncs(Level level){
        List<Region> regions = regionRepository.findAll((root, query, builder) -> builder.equal(root.get("level"), level));
        for (Region region : regions) {
            Info info = findInfo(region.getName(), "1", "base");
            this.regionRepository.saveAll(info.getDistricts().stream().map(District::toRegion).collect(Collectors.toList()));
        }
    }

    private Info findInfo(String keywords, String subdistrict, String extensions){
        String url = "https://restapi.amap.com/v3/config/district";
        Map<String, String> params = new HashMap<>();
        params.put("key", "b7eb9d85d168cdc724b196092b72470f");
        params.put("extensions", extensions);
        params.put("keywords", keywords);
        params.put("subdistrict", subdistrict);
        String string = OkHttpClientUtil.doGetToParams(url, params);

        Info info = JSON.parseObject(string, Info.class);
        System.err.println(info);

        return info;
    }
}
